import time
import logging

from django.http import JsonResponse, QueryDict
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView

from test1.serializers import BepartmentSerializer, UserSerializer


logger = logging.getLogger(__name__)
from django.shortcuts import render

# Create your views here.
from django.views import View

from test1.models import Bepartment, User


class IndexView(View):
    def get(self, request):
        return JsonResponse({"code": 400, 'result': '数据错误', "data": []})


class BepartmentView(APIView):
    """
    部门视图
    查询所有部门
    增加部门
    """
    def get(self, request):
        queryset = Bepartment.objects.all()

        serializer = BepartmentSerializer(queryset, many=True)

        return Response(serializer.data)

    def post(self, request):
        data = request.data  # 获取参数

        serializer = BepartmentSerializer(data=data)
        serializer.is_valid(raise_exception=True)  # 校验
        serializer.save()  # 保存

        return Response(serializer.data)


class BepartmentsView(GenericAPIView):
    """
    查询具体部门
    修改部门
    删除部门
    """
    queryset = Bepartment.objects.all()
    serializer_class = BepartmentSerializer

    def get(self, request, pk):
        # try:
        #     # 查询
        #     benpar_obj = Bepartment.objects.get(id=pk)
        # except Exception as e:
        #     logger.error(e)
        #     return JsonResponse({"code": 400, "result": '无此部门', "data": []})
        #
        # data = {
        #     "id": benpar_obj.id,
        #     "name": benpar_obj.name,
        #     "create_date": benpar_obj.create_date,
        #     "user": benpar_obj.user_set.all()
        # }
        #
        # return JsonResponse({"code": 200, "result": 'OK', "data": data})
        bep = self.get_object()
        serializer = self.get_serializer(bep)

        return Response(serializer.data)

    def put(self, request, pk):
        # put = QueryDict(request.body)
        # name = put.get('name')
        #
        # if not all([name]):
        #     return JsonResponse({"code": 400, "result": '部门名不能为空', "data": []})
        #
        # try:
        #     # 查询部门是否存在
        #     benpar_obj = Bepartment.objects.get(id=pk)
        # except Exception as e:
        #     logger.error(e)
        #     return JsonResponse({"code": 400, "result": '无此部门', "data": []})
        #
        # benpar_obj.name = name
        # benpar_obj.save()
        #
        # data = {
        #     "id": benpar_obj.id,
        #     "name": benpar_obj.name
        # }
        #
        # return JsonResponse({"code": 200, "result": '修改成功', "data": data})
        data = request.data
        try:
            bep = self.get_object()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, "result": '无此部门', "data": []})

        serializer = self.get_serializer(instance=data, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)

    def delete(self, request, pk):
        # try:
        #     # 查询
        #     benpar_obj = Bepartment.objects.get(id=pk)
        # except Exception as e:
        #     logger.error(e)
        #     return JsonResponse({"code": 400, "result": '无此部门', "data": []})
        #
        # benpar_obj.delete()
        #
        # return JsonResponse({"code": 200, "result": '删除成功', "data": []})
        try:
            bep = self.get_object()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"code": 400, "result": '无此部门', "data": []})

        bep.delete()

        return Response(status=status.HTTP_204_NO_CONTENT)


# ListModelMixin        获取全部对象（列表）
# CreateModelMixin      新增资源
# RetrieveModelMixin    获取一个资源
# UpdateModelMixin      更新一个资源
# DestroyModelMixin     删除一个资源


class UsersView(ListModelMixin, CreateModelMixin, GenericAPIView):
    """
    查看所有用户
    新增用户
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)

    # def get(self, request):
    #     quetyset = User.objects.all()
    #     data = []
    #     for i in quetyset:
    #         data.append({
    #             "id": i.id,
    #             "name": i.name,
    #             "age": i.age,
    #             "bepartment": i.bepartment.name,
    #         })
    #
    #     return JsonResponse({"code": 200, "result": 'OK', "data": data})
    #
    # def post(self, request):
    #     name = request.POST.get('name')
    #     age = request.POST.get('age')
    #     pk = request.POST.get('pk')
    #
    #     if not all([name, age, pk]):
    #         return JsonResponse({"code": 400, "result": '缺损参数', "data": []})
    #
    #     try:
    #         age = int(age)
    #         pk = int(pk)
    #     except Exception as e:
    #         logger.error(e)
    #         return JsonResponse({"code": 400, "result": '参数错误', "data": []})
    #
    #     try:
    #         bep_obj = Bepartment.objects.get(id=pk)
    #     except Exception as e:
    #         logger.error(e)
    #         return JsonResponse({"code": 400, "result": '无此部门', "data": []})
    #
    #     user_obj = User.objects.create(
    #         name=name,
    #         age=age,
    #         bepartment=bep_obj
    #     )
    #
    #     data = {
    #         "id": user_obj.id,
    #         "name": user_obj.name,
    #         "age": user_obj.age,
    #         "bepartment": bep_obj.name
    #     }
    #
    #     return JsonResponse({"code": 200, "result": 'OK', "data": data})


class UserView(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView):
    """
    查询单个用户
    修改用户
    删除用户
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get(self, request, pk):
        return self.retrieve(request)

    def put(self, request, pk):
        return self.update(request)

    def delete(self, request, pk):
        return self.destroy(request)

    # def get(self, request, pk):
    #     try:
    #         # 查询
    #         queryset = User.objects.get(id=pk)
    #     except Exception as e:
    #         logger.error(e)
    #         return JsonResponse({"code": 400, "result": '无此用户', "data": []})
    #
    #     data = {
    #         "id": queryset.id,
    #         "name": queryset.name,
    #         "age": queryset.age,
    #         "bepartment": queryset.bepartment.name
    #     }
    #
    #     return JsonResponse({"code": 200, "result": '查询成功', "data": data})
    #
    # def put(self, request, pk):
    #     put = QueryDict(request.body)
    #     name = put.get('name')
    #     age = put.get('age')
    #     bepartment = put.get('bepartment')
    #
    #     if not all([name, age, bepartment]):
    #         return JsonResponse({"code": 400, "result": '缺省参数', "data": []})
    #
    #     try:
    #         age = int(age)
    #         bepartment = int(bepartment)
    #     except Exception as e:
    #         logger.error(e)
    #         return JsonResponse({"code": 400, "result": '参数错误', "data": []})
    #
    #     try:
    #         # 部门
    #         bepar_obj = Bepartment.objects.get(id=bepartment)
    #     except Exception as e:
    #         logger.error(e)
    #         return JsonResponse({"code": 400, "result": '无此部门', "data": []})
    #
    #     try:
    #         # 用户
    #         user_obj = User.objects.get(id=pk)
    #     except Exception as e:
    #         logger.error(e)
    #         return JsonResponse({"code": 400, "result": '无此用户', "data": []})
    #
    #     user_obj.name = name
    #     user_obj.age = age
    #     user_obj.bepartment = bepar_obj
    #     user_obj.save()
    #
    #     data = {
    #         "id": user_obj.id,
    #         "name": user_obj.name,
    #         "age": user_obj.age,
    #         "bepartment": user_obj.bepartment.name
    #     }
    #
    #     return JsonResponse({"code": 200, "result": '修改成功', "data": data})
    #
    # def delete(self, request, pk):
    #     try:
    #         # 查询
    #         user_obj = User.objects.get(id=pk)
    #     except Exception as e:
    #         logger.error(e)
    #         return JsonResponse({"code": 400, "result": '无此用户', "data": []})
    #
    #     user_obj.delete()
    #
    #     return JsonResponse({"code": 200, "result": '删除成功', "data": []})
